package org.example.laboratorymanagement.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.example.laboratorymanagement.mapper.TeacherMapper;
import org.example.laboratorymanagement.pojo.PageBean;
import org.example.laboratorymanagement.pojo.Teacher;
import org.example.laboratorymanagement.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Override
    public void add(Teacher teacher) {
        teacherMapper.insert(teacher);
    }

    @Override
    public void insertBatch(List<Teacher> teachers) {
        // 关闭session的自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class);
            teachers.stream().forEach(teacher -> teacherMapper.insert(teacher));
            // 提交数据
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }
    }

    @Override
    public PageBean pageteachers(Integer page,Integer pageSize,String username, String name) {
        // 设置分页参数
        PageHelper.startPage(page, pageSize);

        List<Teacher> teachers = teacherMapper.listTeachers(username, name);
        Page<Teacher> p = (Page<Teacher>) teachers;

        // 封装PageBean对象
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());

        return pageBean;
    }

    @Override
    public void delete(List<Integer> ids) {
        teacherMapper.delete(ids);
    }

    @Override
    public void update(Teacher teacher) {
        teacherMapper.update(teacher);
    }

    @Override
    public Teacher login(Teacher teacher) {
        return teacherMapper.selectByUnAndPwd(teacher);
    }

    @Override
    public Teacher selectById(Integer id) {
        return teacherMapper.selectById(id);
    }

}
